#include<bits/stdc++.h>
using namespace std;

struct TreeNode {
    int val;
    TreeNode *left;
    TreeNode *right;
    TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};

class Solution {
public:
    TreeNode* inorderSuccessor(TreeNode* root, TreeNode* p) {
        TreeNode* ans = nullptr, *temp = root;
        while(temp){
            if(temp->val > p->val){
                ans = temp;
                temp = temp->left;
            }
            else temp = temp->right;
        }
        return ans;
    }
};

/**
 * @brief 2022.5.16
 * 利用二叉搜索树的性质
 */